/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sarco.bwi;

import com.sarco.bwi.lib.Config;
import com.sarco.bwi.lib.Master;
import com.sarco.bwi.lib.Node;
import com.sarco.bwi.lib.mysql.Mysql;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Unsupported since v0.0.5a
 * @deprecated v0.0.5a
 * @author Andre
 */
public class Main {
    private static Master master = null;
    private static Config config = null;
    private static Mysql mysql = null;
    private static JobThread threadJob = null;
    
    /**
     * @deprecated 
     * @param args 
     */
    public static void main(String[] args) {
        init();
        start();
    }
    
    /**
     * @deprecated 
     */
    private static void init() {
        config = new Config();
        config.loadConfig(Config.DEFAULT_CONFIG);
        master = new Master(config);
        threadJob = new JobThread(master);
    }

    /**
     * @deprecated 
     */
    private static void start() {
        master.waitForConnections();
        threadJob.run();
        if (master.getConfig().isUseMysql())
            initMysql();
        
        System.out.println("Rendering with " + master.getNodes().length + " nodes");
        int nodesdone = 0;
        int nodesleft = master.getNodes().length;
        int[] lastpercent = new int[master.getNodes().length];
        boolean allDone = false;
        
        while (!allDone) {
            for (int i = 0; i < master.getNodes().length; i++) {
                Node n = master.getNodes()[i];
                if (lastpercent[i] != n.getiPercentDone()) {
                    String status = "Node " + i + "(" + n.getSystem() + ") "
                            + n.getiPercentDone() + "%, " + n.getTimeLeft();
                    System.out.println(status);
                    
                    if (master.getConfig().isUseMysql())
                        updateMysql();
                }
                
                lastpercent[i] = n.getiPercentDone();
                
                if (n.getiPercentDone() == 100 && !n.isDone()) {
                    nodesdone++;
                    nodesleft--;
                    allDone = (nodesleft == 0);
                    master.setAllDone(allDone);
                    System.out.println("Node " + i + "(" + n.getHostname() + ") "
                            + "is done!");
                    System.out.println(nodesdone + " nodes is done rendering.");
                    System.out.println("All nodes done? " + allDone);
                    master.getNodes()[i].setDone(true);
                    System.out.println("Waiting for " +
                            (nodesleft) + " nodes.");
                }
            }
        }
        try {
            master.closeAllConnections();
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        System.exit(0);
    }

    /**
     * @deprecated 
     */
    private static void initMysql() {
        mysql = new Mysql();
        mysql.connect(master.getConfig().getMysql_host(), 
                master.getConfig().getMysql_user(), 
                master.getConfig().getMysql_pass(), 
                master.getConfig().getMysql_db());
        try {
            mysql.getStatement().execute("DELETE FROM " + Mysql.Tables.NODE);
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        for (int i = 0; i < master.getNodes().length; i++) {
            Node n = master.getNodes()[i];
            String sql = "INSERT INTO " + 
                    master.getConfig().getMysql_db() + "." + 
                    Mysql.Tables.NODE + " (" + 
                    Mysql.Columns.NODE_CURR_FRAME + ", " +
                    Mysql.Columns.NODE_END_FRAME + ", " +
                    Mysql.Columns.NODE_PERCENT_DONE + ", " +
                    Mysql.Columns.NODE_START_FRAME + ", " +
                    Mysql.Columns.NODE_SYSTEM + ", " +
                    Mysql.Columns.NODE_TIME_LEFT + ", " +
                    Mysql.Columns.NODE_HOSTNAME + ")\n" +
                    "VALUES (" +
                    n.getCurrFrame() + ", " +
                    n.getEndFrame() + ", " +
                    n.getiPercentDone() + ", " +
                    n.getStartFrame() + ", " +
                    ((n.getSystem().length() > 0) ? "'" + n.getSystem() + "'" : "''") + ", " +
                    ((n.getTimeLeft().length() > 0) ? n.getTimeLeft() : "''") 
                    + ", " + 
                    "'" + n.getHostname() + "'" + ");";
            System.out.println("Executing SQL Statement:");
            System.out.println(sql);
            
            String testSql = "INSERT INTO `bwi`.`node` (`curr_frame`, `end_frame`, `percent_done`, `start_frame`, `system`, `time_left`) VALUES (1, 1, 1, 1, 'Windows', '00:11:11');";
            try {
                mysql.getStatement().execute(sql);
                mysql.fetchNodeData();               
            } catch (SQLException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        // Get node id:
        {
            Node[] nodes = mysql.getNodes();
            for (int i = 0; i < master.getNodes().length; i++) {
                master.getNodes()[i].setId(nodes[i].getId());
            }
        }
        
        try {
            mysql.closeConnection();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /**
     * @deprecated 
     **/
    private static void updateMysql() {
        mysql.connect(master.getConfig().getMysql_host(), 
                master.getConfig().getMysql_user(), 
                master.getConfig().getMysql_pass(), 
                master.getConfig().getMysql_db());
        
        for (int i = 0; i < master.getNodes().length; i++) {
            Node n = master.getNodes()[i];
            String sql = "UPDATE " + master.getConfig().getMysql_db() + "." + Mysql.Tables.NODE + "\n" +
                    "SET " + 
                    Mysql.Columns.NODE_CURR_FRAME + "=" + n.getCurrFrame() + ", " +
                    Mysql.Columns.NODE_PERCENT_DONE + "=" + n.getiPercentDone() + ", " +
                    Mysql.Columns.NODE_TIME_LEFT + "='" + n.getTimeLeft() + "'\n" +
                    "WHERE " + 
                    Mysql.Columns.NODE_IDNODE + "=" + n.getId() + ";";
            System.out.println("Executing SQL Statement:");
            System.out.println(sql);
            try {
                mysql.getStatement().execute(sql);
                mysql.fetchNodeData();
            } catch (SQLException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            mysql.closeConnection();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
